/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.help.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.file.provider.BizFileApiProvider;
import vip.xiaonuo.biz.modular.help.entity.BizHelpFamily;
import vip.xiaonuo.biz.modular.help.mapper.BizHelpFamilyMapper;
import vip.xiaonuo.biz.modular.help.param.*;
import vip.xiaonuo.biz.modular.help.service.BizHelpFamilyService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.help.entity.BizHelp;
import vip.xiaonuo.biz.modular.help.mapper.BizHelpMapper;
import vip.xiaonuo.biz.modular.help.service.BizHelpService;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 困难职工申请Service接口实现类
 *
 * @author 薛守立
 * @date  2024/08/22 08:47
 **/
@Service
public class BizHelpServiceImpl extends ServiceImpl<BizHelpMapper, BizHelp> implements BizHelpService {
    @Autowired
    BizHelpFamilyMapper bizHelpFamilyMapper;

    @Resource
    private BizHelpFamilyService bizHelpFamilyService;

    @Resource
    private BizFileApiProvider bizFileApiProvider;

    @Resource
    private SysUserApi sysUserApi;

    @Override
    public Page<BizHelp> page(BizHelpPageParam bizHelpPageParam) {
        QueryWrapper<BizHelp> queryWrapper = new QueryWrapper<BizHelp>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizHelpPageParam.getUserName())) {
            queryWrapper.lambda().like(BizHelp::getUserName, bizHelpPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(bizHelpPageParam.getWorkOrg())) {
            queryWrapper.lambda().like(BizHelp::getWorkOrg, bizHelpPageParam.getWorkOrg());
        }
        if(ObjectUtil.isAllNotEmpty(bizHelpPageParam.getSortField(), bizHelpPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizHelpPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizHelpPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizHelpPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizHelp::getId);
        }
        // 这里后面做调整 不查询longText 否则效率低
        // queryWrapper.select("id", "name", "email");
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }
    @Override
    public Page<BizHelp> applyPage(BizHelpPageParam bizHelpPageParam) {
        QueryWrapper<BizHelp> queryWrapper = new QueryWrapper<BizHelp>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizHelpPageParam.getUserName())) {
            queryWrapper.lambda().like(BizHelp::getUserName, bizHelpPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(bizHelpPageParam.getWorkOrg())) {
            queryWrapper.lambda().like(BizHelp::getWorkOrg, bizHelpPageParam.getWorkOrg());
        }

        if(ObjectUtil.isAllNotEmpty(bizHelpPageParam.getSortField(), bizHelpPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizHelpPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizHelpPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizHelpPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizHelp::getId);
        }
        // 查询待审批
        queryWrapper.gt("status",0);
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizHelpAddParam bizHelpAddParam) {

        BizHelp bizHelp = BeanUtil.toBean(bizHelpAddParam, BizHelp.class);
        // 默认状态
        bizHelp.setStatus(0);
        this.save(bizHelp);

        // 添加文件
        List<String> fileList = bizHelpAddParam.getFileList();
        for(String fileId : fileList){
            bizFileApiProvider.updateFile(fileId, bizHelp.getId(), "困难用户申请文件");
        }
        // 保存文件地址
        String fileUrl = bizFileApiProvider.getFileUrl(fileList.get(0));
        JSONObject sysOrg = sysUserApi.getUserOrg(bizHelp.getCreateUser());
        Map orgMap = sysOrg.toBean(Map.class);
        bizHelp.setOrgId((String) orgMap.get("id"));
        bizHelp.setFileUrl(fileUrl);

        if(bizHelp.getBizHelpFamilyList()!=null){
            for(BizHelpFamily bizHelpFamily:bizHelp.getBizHelpFamilyList()){
                bizHelpFamily.setId(null);
                bizHelpFamily.setHeipId(bizHelp.getId());
            }
            bizHelpFamilyService.saveBatch(bizHelp.getBizHelpFamilyList());
        }
        this.updateById(bizHelp);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizHelpEditParam bizHelpEditParam) {
        BizHelp bizHelp = this.queryEntity(bizHelpEditParam.getId());
        QueryWrapper<BizHelpFamily> bizHelpFamilyQueryWrapper = new QueryWrapper<>();
        bizHelpFamilyQueryWrapper.eq("heip_id",bizHelp.getId());
        bizHelpFamilyService.remove(bizHelpFamilyQueryWrapper);

        BeanUtil.copyProperties(bizHelpEditParam, bizHelp);
        this.updateById(bizHelp);
        for(BizHelpFamily bizHelpFamily :bizHelp.getBizHelpFamilyList()){
            bizHelpFamily.setHeipId(bizHelp.getId());
            bizHelpFamily.setId(null);
        }
        // 保存家庭成员信息
        bizHelpFamilyService.saveBatch(bizHelp.getBizHelpFamilyList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizHelpIdParam> bizHelpIdParamList) {
        Map<String, Object> params = new HashMap<>();
        // 执行删除
        for (BizHelpIdParam bizHelpIdParam:bizHelpIdParamList){
            QueryWrapper<BizHelpFamily> bizHelpFamilyQueryWrapper = new QueryWrapper<>();
            bizHelpFamilyQueryWrapper.eq("heip_id",bizHelpIdParam.getId());
            bizHelpFamilyService.remove(bizHelpFamilyQueryWrapper);
        }

      this.removeByIds(CollStreamUtil.toList(bizHelpIdParamList, BizHelpIdParam::getId));
    }

    @Override
    public BizHelp detail(BizHelpIdParam bizHelpIdParam) {
        BizHelp bizHelp= this.queryEntity(bizHelpIdParam.getId());
        Map<String, Object> params = new HashMap<>();
        params.put("HEIP_ID", bizHelpIdParam.getId());
         List<BizHelpFamily> bizHelpFamilyList =  bizHelpFamilyMapper.selectByMap(params);
        bizHelp.setBizHelpFamilyList(bizHelpFamilyList);

        return bizHelp;
    }

    @Override
    public BizHelp queryEntity(String id) {
        BizHelp bizHelp = this.getById(id);
        if(ObjectUtil.isEmpty(bizHelp)) {
            throw new CommonException("困难职工申请不存在，id值为：{}", id);
        }
        return bizHelp;
    }

    @Override
    public void apply(BizHelpApplyParam bizHelpApplyParam) {
        BizHelp bizHelp= this.queryEntity(bizHelpApplyParam.getId());
        BeanUtil.copyProperties(bizHelpApplyParam, bizHelp);
        this.updateById(bizHelp);
    }


}